package com.learn.sixday;

import org.apache.log4j.Logger;

import java.util.concurrent.TimeUnit;

/**
 * @author ln
 * @Description: ${todo}
 * @date 2020/12/12
 */
public class TestWaitNotify {
    final static Logger logger=Logger.getLogger(TestWaitNotify.class);

    final static Object obj=new Object();

    public static void main(String[] args) {

        new Thread(()->{
            synchronized (obj){
                logger.debug("t1执行....");
                try {
                    obj.wait();//让线程在obj上一直等待下去,它会释放锁
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                logger.debug("其他代码....");
            }

        },"t1").start();

        new Thread(()->{
            synchronized (obj){
                logger.debug("t2执行....");
                try {
                    obj.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                logger.debug("其他代码....");
            }

        },"t2").start();


//        主线程2秒后执行
        try {
            TimeUnit.SECONDS.sleep(2);
            logger.debug("唤醒obj上其他线程");
            synchronized (obj){
                obj.notify();//唤醒obj上一个线程
//                obj.notifyAll();//唤醒obj上所有等待的线程
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
